from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify, current_app
import json
from flask_login import current_user
from ..utils import admin_required
from ..models import User, Book, db, ReturnRequest, BorrowRecord, BorrowRequest
from sqlalchemy.exc import IntegrityError
from datetime import datetime
from sqlalchemy.orm import joinedload
from datetime import datetime, timedelta  # 添加timedelta导入
from werkzeug.security import generate_password_hash

bp = Blueprint('admin', __name__, url_prefix='/admin')

@bp.route('/')
@admin_required
def dashboard():
    return render_template('admin/admin.html')

@bp.route('/users')
@admin_required
def manage_users():
    users = User.query.all()
    return render_template('admin/users.html', users=users)

@bp.route('/settings', methods=['GET', 'POST'])
@admin_required
def settings():
    if request.method == 'POST':
        site_name = request.form['site_name']
        maintenance_mode = request.form['maintenance_mode']
        # 这里假设你有一个SiteSetting模型来存储这些设置
        # site_setting = SiteSetting.query.first()
        # site_setting.site_name = site_name
        # site_setting.maintenance_mode = maintenance_mode
        # db.session.commit()
        flash('系统设置已保存', 'success')
        return redirect(url_for('admin.settings'))
    return render_template('admin/settings.html')

@bp.route('/books')
@admin_required
def manage_books():
    books = Book.query.all()
    return render_template('admin/books.html', books=books)

@bp.route('/users/add', methods=['GET', 'POST'])
@admin_required
def add_user():
    if request.method == 'POST':
        username = request.form['username']
        password = generate_password_hash(request.form['password'])
        is_admin = 'is_admin' in request.form

        # 检查用户名是否已存在
        existing_user = User.query.filter_by(username=username).first()
        if existing_user:
            flash('用户名已存在，不能添加', 'danger')
            return redirect(url_for('admin.add_user'))

        new_user = User(username=username, password=password, is_admin=is_admin)
        try:
            db.session.add(new_user)
            db.session.commit()
            flash('用户已添加', 'success')
            return redirect(url_for('admin.manage_users'))
        except IntegrityError:
            db.session.rollback()
            flash('用户名已存在，不能添加', 'danger')
            return redirect(url_for('admin.add_user'))

    return render_template('admin/add_user.html')

@bp.route('/users/edit/<int:user_id>', methods=['GET', 'POST'])
@admin_required
def edit_user(user_id):
    user = User.query.get_or_404(user_id)
    if request.method == 'POST':
        user.username = request.form['username']
        user.password = request.form['password']
        user.is_admin = 'is_admin' in request.form
        db.session.commit()
        flash('用户已更新', 'success')
        return redirect(url_for('admin.manage_users'))
    return render_template('admin/edit_user.html', user=user)

@bp.route('/users/delete/<int:user_id>', methods=['POST'])
@admin_required
def delete_user(user_id):
    user = User.query.get_or_404(user_id)
    db.session.delete(user)
    db.session.commit()
    flash('用户已删除', 'success')
    return redirect(url_for('admin.manage_users'))

@bp.route('/books/add', methods=['GET', 'POST'])
@admin_required
def add_book():
    if request.method == 'POST':
        title = request.form['title']
        author = request.form['author']
        new_book = Book(title=title, author=author)
        db.session.add(new_book)
        db.session.commit()
        flash('图书已添加', 'success')
        return redirect(url_for('admin.manage_books'))
    return render_template('admin/add_book.html')

@bp.route('/books/edit/<int:book_id>', methods=['GET', 'POST'])
@admin_required
def edit_book(book_id):
    book = Book.query.get_or_404(book_id)
    if request.method == 'POST':
        book.title = request.form['title']
        book.author = request.form['author']
        db.session.commit()
        flash('图书已更新', 'success')
        return redirect(url_for('admin.manage_books'))
    return render_template('admin/edit_book.html', book=book)

@bp.route('/books/delete/<int:book_id>', methods=['POST'])
@admin_required
def delete_book(book_id):
    book = Book.query.get_or_404(book_id)
    db.session.delete(book)
    db.session.commit()
    flash('图书已删除', 'success')
    return redirect(url_for('admin.manage_books'))


@bp.route('/borrow_requests', endpoint='borrow_requests')
@admin_required
def get_borrow_requests():
    print(f"当前用户：{current_user.id}, 查询待处理申请")

    # 使用joinedload预加载关联对象
    requests = BorrowRequest.query.options(
        joinedload(BorrowRequest.requester),
        joinedload(BorrowRequest.book)
    ).filter_by(status='pending').all()

    # 调试输出
    print(f"查询到{len(requests)}条申请：")
    for req in requests:
        print(f"ID:{req.id}, 用户:{req.requester.username}, 图书:{req.book.title}, Notes:{req.notes}")

    return render_template('admin/borrow_requests.html', requests=requests)


@bp.route('/approve_borrow/<int:request_id>', methods=['POST'])
@admin_required
def approve_borrow(request_id):
    return _process_borrow_request(request_id, 'approved')

@bp.route('/reject_borrow/<int:request_id>', methods=['POST'])
@admin_required
def reject_borrow(request_id):
    return _process_borrow_request(request_id, 'rejected')

def _process_borrow_request(request_id, status):
    try:
        # 获取借阅申请
        borrow_request = BorrowRequest.query.get_or_404(request_id)
        book = Book.query.get_or_404(borrow_request.book_id)

        # 验证图书可用性（仅在批准时验证）
        if status == 'approved' and book.available_copies <= 0:
            flash('图书副本已全部借出', 'danger')
            return redirect(url_for('admin.borrow_requests'))

        # 更新申请状态
        borrow_request.status = status
        borrow_request.processed_by = current_user.id
        borrow_request.process_time = datetime.utcnow()

        # 创建借阅记录（仅在批准时创建）
        if status == 'approved':
            new_record = BorrowRecord(
                book_id=borrow_request.book_id,
                user_id=borrow_request.user_id,
                borrow_date=datetime.utcnow(),
                due_date=datetime.utcnow() + timedelta(days=14),
                status='borrowed',
                processed_by=current_user.id
            )
            db.session.add(new_record)

            # 更新图书库存
            book.available_copies -= 1
            if book.available_copies <= 0:
                book.status = 'borrowed'

        db.session.commit()

        flash(f'《{book.title}》借阅申请已{status}', 'success')
        return redirect(url_for('admin.borrow_requests'))

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"处理借阅申请失败: {str(e)}", exc_info=True)
        flash(f'处理失败: {str(e)}', 'danger')
        return redirect(url_for('admin.borrow_requests'))


@bp.route('/return_requests')
@admin_required
def return_requests():
    requests = ReturnRequest.query \
        .options(
        joinedload(ReturnRequest.borrow_record).joinedload(BorrowRecord.book),
        joinedload(ReturnRequest.submitter)
    ) \
        .filter_by(status='pending') \
        .all()

    return render_template('admin/return_requests.html', requests=requests)


@bp.route('/approve_return/<int:request_id>', methods=['POST'])
@admin_required
def approve_return(request_id):
    try:
        return_request = ReturnRequest.query.get_or_404(request_id)
        borrow_record = return_request.borrow_record

        # 更新归还申请状态
        return_request.status = 'approved'
        return_request.process_time = datetime.utcnow()
        return_request.admin_id = current_user.id

        # 更新借阅记录状态
        borrow_record.status = 'returned'
        borrow_record.return_date = datetime.utcnow()

        # 更新图书库存
        book = borrow_record.book
        book.available_copies += 1
        if book.available_copies > 0:
            book.status = 'available'

        db.session.commit()

        flash('归还申请已批准', 'success')
        return redirect(url_for('admin.return_requests'))

    except Exception as e:
        db.session.rollback()
        flash(f'处理失败: {str(e)}', 'danger')
        return redirect(url_for('admin.return_requests'))


@bp.route('/reject_return/<int:request_id>', methods=['POST'])
@admin_required
def reject_return(request_id):
    try:
        return_request = ReturnRequest.query.get_or_404(request_id)
        borrow_record = return_request.borrow_record

        # 更新归还申请状态
        return_request.status = 'rejected'
        return_request.process_time = datetime.utcnow()
        return_request.admin_id = current_user.id

        # 将借阅记录状态恢复为借出中
        borrow_record.status = 'borrowed'

        db.session.commit()

        flash('归还申请已拒绝', 'success')
        return redirect(url_for('admin.return_requests'))

    except Exception as e:
        db.session.rollback()
        flash(f'处理失败: {str(e)}', 'danger')
        return redirect(url_for('admin.return_requests'))


